--[[
    NuckPluck - An android game for learning the Thai alphabet
    Copyright (C) 2013 Nathan Kieffer

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

    Contact: nathankieffer@gmail.com
--]]

local physics = require("physics")
physics.start()
local Player = {}

function Player.newPlayer()
   local player = display.newGroup()
   player.shape = display.newImage(player, "images/player.png")
   player.name = "Player"
   player.type = "player"
   player.collisions = 0
   player.isFalling = false
   player.lives = 3
   player.isInvincible = false
   player.invincibleTimer = timer.performWithDelay(0, function() end)
   player.flash = -0.2

   function player:move(x, y, angle)
      self.x = self.x + x
      self.y = self.y + y
      self.rotation = angle
   end
   function player:collision(event)
      --check for collisions with air tiles and enemies

      if not self.isInvincible then
	 if event.other.type == "enemy" then
	    print("falling")
	    self.lives = self.lives - 1
	    self.isFalling = true
	    timer.cancel(self.invincibleTimer)
	    self:invincible()
	 end
      end
      if event.other.subtype == "air" then
	 self.lives = self.lives - 1
	 self.isFalling = true
	 timer.cancel(self.invincibleTimer)
	 self:invincible()
      end
   end

   function player:invincible(event)
      --makes player invincible for 3 seconds after contact with enemy
      self.isInvincible = true
      self.invincibleTimer = timer.performWithDelay(3000, function(event)
				self.isInvincible = false
				self.alpha = 1
				   end)
   end
   
   function player:enterFrame(event)
      --flash the player if invincible
      if self.isInvincible then
	 self.alpha = self.alpha + self.flash
      end
      if self.alpha >= 1 or self.alpha <= 0 then
	 self.flash = self.flash * -1
      end
   end

   Runtime:addEventListener("enterFrame", player)
   player:addEventListener("collision", player)
   physics.addBody(player, "dynamic", {isSensor=false, density=1, bounce=1,
					filter={ categoryBits=1,
						 maskBits=124 }})

   return player
end

return Player